package com.zackeus.common.utils;

import android.util.Base64;

import java.nio.charset.StandardCharsets;

/**
 * 编解码工具
 * @name: Codec
 * @author: zz
 * @date: 2022/9/19
 */
public class Codec {

    private final char[] BASE62;

    private static volatile Codec mInstance;

    private Codec() {
        this.BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
    }

    public static Codec getInstance() {
        if (mInstance == null) {
            synchronized (Codec.class) {
                if (mInstance == null) {
                    mInstance = new Codec();
                }
            }
        }
        return mInstance;
    }

    /**
     * Base62 编码
     * @param input
     * @return
     */
    public String encodeBase62(byte[] input) {
        char[] chars = new char[input.length];
        for (int i = 0; i < input.length; i++) {
            chars[i] = this.BASE62[((input[i] & 0xFF) % this.BASE62.length)];
        }
        return new String(chars);
    }

    public String encodeBase64(String str) {
        return this.encodeBase64(str.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * Base64 编码
     * @param input
     * @return
     */
    public String encodeBase64(byte[] input) {
        return Base64.encodeToString(input, Base64.DEFAULT);
    }

    public String decodeBase64ToString(String str) {
        return new String(this.decodeBase64(str));
    }

    /**
     * Base64 解码
     * @param str
     * @return
     */
    public byte[] decodeBase64(String str) {
        return Base64.decode(str.getBytes(StandardCharsets.UTF_8), Base64.DEFAULT);
    }
}
